import { ref, reactive, createVNode } from "vue";
// 导入提示方法
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
// 导入修改头像接口
import { updateAvatar } from "@/api/userAPI";
// 导入vuex
import { useStore } from "vuex";

export const useEditAvatar = (id) => {
  // 修改头像弹框显示状态
  const editVisible = ref(false);

  // 上传状态
  const loading = ref(false);

  // 图片预览地址
  const imageUrl = ref("");

  // 点击修改头像
  const handleEditAvatar = () => {
    editVisible.value = true;
  };

  // 表单内容
  const editModel = reactive({
    avatar: [],
  });

  // 存储上传后的图片地址
  const user_avatar = ref("");

  // 表单ref
  const editFormRef = ref(null);

  // 关闭模态框
  const editCloselModal = () => {
    editFormRef.value.resetFields();
  };

  // 校验规则
  const editFormRules = ref({
    avatar: [
      {
        required: true,
        message: "图片不能为空",
      },
    ],
  });

  // 转 base64格式
  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  // 上传文件改变时的状态
  const handleChange = (info) => {
    // 上传中
    if (info.file.status === "uploading") {
      loading.value = true;
      return;
    }
    // 上传完成
    if (info.file.status === "done") {
      getBase64(info.file.originFileObj, (base64Url) => {
        imageUrl.value = base64Url;
        loading.value = false;
      });
      user_avatar.value = info.file.response.data.filename;
    }
    // 上传错误
    if (info.file.status === "error") {
      loading.value = false;
      message.error("upload error");
    }
  };

  // 使用vuex
  const store = useStore();

  // 点击确认
  const handleOk = () => {
    editFormRef.value
      .validate()
      .then(() => {
        // 二次确认
        Modal.confirm({
          title: "确认提示",
          icon: createVNode(ExclamationCircleOutlined),
          content: "您是否确认修改头像",
          okText: "确认",
          cancelText: "取消",
          onOk() {
            // 参数
            const params = {
              id,
              avatar: user_avatar.value,
            };
            // 发送请求修改头像
            updateAvatar(params)
              .then((res) => {
                message.success(res.msg);
                if (res.status === 200) {
                  // 修改vuex中用户信息
                  let newAvatar = store.state.userStore.userInfos;
                  newAvatar.avatar = user_avatar.value;
                  store.commit("userStore/SET_USERINFOS", newAvatar);
                  editVisible.value = false;
                }
              })
              .catch((error) => {
                throw new Error(error);
              });
          },
          onCancel() {
            message.info("已取消");
          },
        });
      })
      .catch((error) => {
        throw new Error(error);
      });
  };

  return {
    editVisible,
    loading,
    imageUrl,
    handleEditAvatar,
    editModel,
    editFormRef,
    editCloselModal,
    editFormRules,
    handleChange,
    handleOk,
  };
};
